/**
    @project {
        "templateId": "org.helgoboss.custom",
        "version": "0.1-SNAPSHOT",
        "dependencies": [
            "org.scala-lang:scala-library:2.9.0-1",
            "org.helgoboss:scala-additions:0.1-SNAPSHOT",
            "org.helgoboss:osgi-additions:0.1-SNAPSHOT",
            "org.helgoboss:mini-obr-runtime:0.1-SNAPSHOT",
            "org.apache.felix:org.osgi.service.obr:1.0.2",
            "org.helgoboss:obr-facade-api:0.3-SNAPSHOT",
            "org.helgoboss:commandlet-manager:0.1-SNAPSHOT"
        ]
    }
*/

package org.helgoboss.mini_obr_runtime_bootstrapper

import org.helgoboss.scala_additions.Implicits._
import org.helgoboss.osgi_additions._
import org.helgoboss.mini_obr_runtime._
import org.osgi.service.obr.RepositoryAdmin
import org.helgoboss.obr_facade._
import org.helgoboss.commandlet_manager._


class Activator extends OsgiContext with OsgiServiceWatcher {
    whenBundleActive {
        whenServicesPresent[MiniObrRuntime, RepositoryAdmin, ObrFacade] { (miniObrRuntime, repositoryAdmin, obrFacade) =>
            println("Ready ...")
            miniObrRuntime.repositories.foreach(repositoryAdmin.addRepository)
            miniObrRuntime.resources.foreach(obrFacade.switchOnResource)
            
            miniObrRuntime.commandletId.foreach { id =>
                whenServicePresent[CommandletManager] { commandletManager =>
                    val commandlet = commandletManager.findCommandlet(id)
                    commandlet match {
                        case Some(c) =>
                            val exitCode = c.execute(miniObrRuntime.commandletExecutionContext)
                            miniObrRuntime.stop(exitCode)
                        case None =>
                            error("no commandlet found for specified commandletId")
                    }
                }
            }
        }
    }
}